package com.godyao.security.jwt.handler;

import com.godyao.model.LoginToken;
import com.godyao.enums.ResultMsg;
import com.godyao.utils.JwtUtils;
import com.godyao.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author godyao
 * @date 2022/3/16
 */
@Component
@Slf4j
public class LoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        final UserDetails principal = (UserDetails) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 生产令牌
        String accessToken = jwtUtils.createToken(principal.getUsername());
        // 生成刷新令牌,如果accessToken过期则可以使用下面的refreshToken重新请求获取新的有效token（改有效期要比accessToken的有效期长）
        String refreshToken = jwtUtils.refreshToken(accessToken);
        renderToken(httpServletResponse, LoginToken.builder().accessToken(accessToken).refreshToken(refreshToken).build());
    }

    private void renderToken(HttpServletResponse httpServletResponse, LoginToken token) throws IOException {
        ResponseUtils.result(httpServletResponse, new ResultMsg(200, "登录成功", token));
    }


}
